#include <stdio.h>
#include "ohos_init.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"

#include "cmsis_os2.h"


unsigned char CodeArr[8] = { //步进电机节拍对应的 IO 控制代码
	0xC, 0x6, 0x3, 0x9, 0xC, 0x6, 0x3, 0x9
};

void moto(void* args ){
    int i;
    printf("moto thread running...");
    for(i=7;i<=12;i++){
        IoTGpioInit(i);
        IoTGpioSetDir(i,IOT_GPIO_DIR_OUT);
        IoTGpioSetFunc(i,0);
        IoTGpioSetOutputVal(i,0);
    }    
    //IoTGpioSetFunc(13,IOT_GPIO_FUNC_GPIO_13_GPIO);
    int c = 9;
    int idx = 0;
    while(1){
        unsigned char code = CodeArr[idx];
        for(i = 9;i<=12;i++){
            printf("set port%d to %d\n" , i , code & 0x1);
            IoTGpioSetOutputVal(i,code & 0x1);
            //usleep(200*1000);
            code = code >> 1;
        }
        printf("sleep");
        usleep(1000);
        idx = (idx+1)%8;
    }
}

void moto_entry(){
    printf("moto_entry called \n");

    osThreadAttr_t attr;

    attr.name = "thread_moto";
    attr.attr_bits = 0U; // 如果为1 ，则可以使用osThreadJoin函数
    attr.cb_mem = NULL; //控制快的指针
    attr.cb_size = 0U;
    attr.stack_mem = NULL; //栈内存指针
    attr.stack_size = 1024 * 4; //栈大小
    attr.priority = 25; //优先级

    if (osThreadNew((osThreadFunc_t)moto, NULL, &attr) == NULL)
    {
        printf("Falied to create thread!\n");
    }
}

APP_FEATURE_INIT(moto_entry);

